package com.github.postsanf.yinian.activity;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.github.postsanf.yinian.ElseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.activity.pop.PopSetAvatar;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.entity.YNCommonResponse;
import com.github.postsanf.yinian.entity.YNUpTokenResponse;
import com.github.postsanf.yinian.utils.Crop;
import com.github.postsanf.yinian.utils.ImageUtils;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.StringUtils;
import com.github.postsanf.yinian.utils.SystemUtils;
import com.github.postsanf.yinian.utils.ToastUtils;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONObject;

import java.io.File;
import java.util.LinkedHashMap;
import java.util.UUID;

public class ReMainGiftActivity extends ElseActivity implements View.OnClickListener {
    private ImageView addImageView;
    private File mTempDir;
    private PopSetAvatar mpopSetAvatar;
    private String imagelocal;
    private ProgressDialog mProgressDialog;
    private UploadManager mUpManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.yn_remain_gift);
        mUpManager = application.getUploadManager();
        mTempDir = new File(Environment.getExternalStorageDirectory(), "yinian/temp");
        if (!mTempDir.exists()) {
            mTempDir.mkdirs();
        }
        initView();
    }


    private void initView() {
        mpopSetAvatar = new PopSetAvatar(ReMainGiftActivity.this, itemsOnClick, itemsOnTouch);
        findViewById(R.id.gift_get).setOnClickListener(this);
        findViewById(R.id.gift_cancel).setOnClickListener(this);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.gift_get:
                final Dialog dialog = new Dialog(this, R.style.dialog_remain_gift);
                final View dView = getLayoutInflater().inflate(R.layout.yn_remain_gift_face, null);
                addImageView = (ImageView) dView.findViewById(R.id.gift_face_add);
                addImageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        uploadSEcondGiftPacket();
                        mpopSetAvatar.showAtLocation(dView.findViewById(R.id.main_buttom), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                        ((TextView) mpopSetAvatar.mMenuView.findViewById(R.id.btn_alert_avatar_title)).setText("添加照片");
                    }
                });
                dView.findViewById(R.id.gift_face_next).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (picUrl != null && !picUrl.equals("")) {
                            UploadGiftContent(picUrl);
                            dialog.dismiss();
                        } else {
                            showToast("未添加图片");
                        }
                    }
                });
                dView.findViewById(R.id.gift_cancel).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dialog.dismiss();
                    }
                });
                dialog.setContentView(dView);
                dialog.show();
                break;
            case R.id.gift_cancel:
                final Dialog canceldialog = new Dialog(this, R.style.dialog_remain_gift);
                final View cancelView = getLayoutInflater().inflate(R.layout.yn_remain_gift_close_tip, null);
                cancelView.findViewById(R.id.gift_close_no).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //记录拒绝
                        uploadSEcondGiftPacket();
                        finish();
                    }
                });
                cancelView.findViewById(R.id.gift_close_yes).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        canceldialog.dismiss();
                    }
                });
                canceldialog.setContentView(cancelView);
                canceldialog.show();
                break;
        }
    }

    private void UploadGiftContent(final String picUrl) {
        final Dialog dialog = new Dialog(this, R.style.dialog_remain_gift);
        final View dView = getLayoutInflater().inflate(R.layout.yn_remain_gift_content, null);
        final EditText nameEt = (EditText) dView.findViewById(R.id.gift_content_name);
        final EditText phoneEt = (EditText) dView.findViewById(R.id.gift_content_phone);
        final EditText addressEt = (EditText) dView.findViewById(R.id.gift_content_address);
        dView.findViewById(R.id.gift_content_save).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String name = nameEt.getText().toString();
                String phone = phoneEt.getText().toString();
                String address = addressEt.getText().toString();
                if (StringUtils.isEmptyString(name)) {
                    showToast("姓名不能为空");
                    return;
                }
                if (StringUtils.isEmptyString(phone)) {
                    showToast("电话不能为空");
                    return;
                }
                if (StringUtils.isEmptyString(address)) {
                    showToast("地址不能为空");
                    return;
                }
                if (SystemUtils.isFastClick()) {
                    return;
                }
                postUploadGiftContent(name, phone, address, picUrl);
            }
        });
        dialog.setContentView(dView);
        dialog.show();
    }

    boolean flag = true;

    private void postUploadGiftContent(String name, String phone, String address, String picUrl) {
        if (flag == false) {
            return;
        }
        flag = false;
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        mParam.put(CommonConstants.YNS_NICKNAME, application.getCurUser().getUnickname());
        mParam.put(CommonConstants.YNS_REALNAME, name);
        mParam.put(CommonConstants.YNS_PHONE_NUM, phone);
        mParam.put(CommonConstants.YNS_ADDRESS, address);
        mParam.put(CommonConstants.YNS_PICURL, picUrl);
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynUploadGiftContent))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNCommonResponse resAlertBg = gson.fromJson(s, YNCommonResponse.class);
                        if (ReqUtils.isSuccess(resAlertBg.getCode())) {
                            flag = true;
                            Toast toast = Toast.makeText(ReMainGiftActivity.this, "你的愿望忆年马上帮你实现~", Toast.LENGTH_LONG);
                            toast.setGravity(Gravity.CENTER, 0, 1);
                            toast.show();
                            finish();
                        } else {
                            showToast("失败");
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
//                        showToast(CommonConstants.YN_NET_LINK);

                    }

                    @Override
                    public void onEnd(Response<String> response) {
                        super.onEnd(response);

                    }
                });
        liteHttp.executeAsync(req);
    }


    private void uploadSEcondGiftPacket() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynGetSecondGiftPacket))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNCommonResponse resAlertBg = gson.fromJson(s, YNCommonResponse.class);
//                        if (ReqUtils.isSuccess(resAlertBg.getCode())) {
//                            showToast("成功");
//                        } else {
//                            showToast("失败");
//                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    private View.OnTouchListener itemsOnTouch = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            int height = mpopSetAvatar.mMenuView.findViewById(R.id.pop_setuser_advatar_layout).getTop();
            int y = (int) event.getY();
            if (event.getAction() == MotionEvent.ACTION_UP) {
                if (y < height) {
                    mpopSetAvatar.dismiss();
                }
            }
            return true;
        }
    };


    private void handleCrop(int resultCode, Intent result) {
        if (resultCode == Activity.RESULT_OK) {
            imagelocal = ImageUtils.getImageAbsolutePath19(this, Crop.getOutput(result));
            imageLoader.displayImage("file:///" + imagelocal, addImageView);
            getToken();
        } else if (resultCode == Crop.RESULT_ERROR) {
            ToastUtils.showToast(this, "处理图片失败", Toast.LENGTH_SHORT);
        }
    }

    private void beginCrop(Uri source) {
        String fileName = "Temp_" + String.valueOf(System.currentTimeMillis()) + ".png";
        File cropFile = new File(mTempDir, fileName);
        Uri outputUri = Uri.fromFile(cropFile);
        new Crop(source).output(outputUri).asSquare().setCropType(false).start(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case ImageUtils.REQUEST_CODE_FROM_ALBUM:
                if (resultCode == RESULT_CANCELED) {
                    return;
                }
                Uri imageUri = data.getData();
                beginCrop(imageUri);
                break;
            case ImageUtils.REQUEST_CODE_FROM_CAMERA:
                if (resultCode == RESULT_CANCELED) {
                    ImageUtils.deleteImageUri(this, ImageUtils.imageUriFromCamera);
                } else {
                    Uri imageUriCamera = ImageUtils.imageUriFromCamera;
                    beginCrop(imageUriCamera);
                }
                break;
            case Crop.REQUEST_CROP:
                handleCrop(resultCode, data);
                break;
            default:
                break;
        }
    }

    // 获取上传Token
    private void getToken() {
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynGetUploadToken))
                .setMethod(HttpMethods.Post)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNUpTokenResponse resToken = gson.fromJson(s, YNUpTokenResponse.class);
                        if (ReqUtils.isSuccess(resToken.getCode())) {
                            application.setUpToken(resToken.getData().get(0).getToken());
                            getAvatarAddress();
                        } else {
                            showToast(resToken.getMsg());
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    private String picUrl;

    // 获取七牛云头像地址
    private void getAvatarAddress() {
        mProgressDialog = ProgressDialog.show(this, "", CommonConstants.TIP_LOAD_UP);
        String prefix = imagelocal.substring(imagelocal.lastIndexOf(".") + 1);
        final String imgName = UUID.randomUUID().toString() + "." + prefix;
        mUpManager.put(imagelocal, imgName, application.getUpToken(),
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        picUrl = key;
                        mProgressDialog.dismiss();
                    }

                }, new UploadOptions(null, null, false,
                        new UpProgressHandler() {
                            public void progress(String key, double percent) {

                            }
                        }, null));
    }


    // 头像监听
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {
        public void onClick(View v) {
            mpopSetAvatar.dismiss();
            switch (v.getId()) {
                case R.id.btn_setuser_take_photo:
                    ImageUtils.pickImageFromCamera(ReMainGiftActivity.this);
                    break;
                case R.id.btn_setuser_pick_photo:
                    ImageUtils.pickImageFromAlbum(ReMainGiftActivity.this);
                    break;
            }
        }
    };


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }
}
